package com.yzmoney.wechat.service;

import com.yzmoney.common.constant.Constants;
import com.yzmoney.common.util.JDKStackTrace;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Service;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;

@Service
public class WechatVerifyService {
    private static Logger logger = Logger.getLogger(WechatVerifyService.class);
    /*
    signature  微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数。
	timestamp  时间戳  
	nonce  随机数  
	echostr  随机字符串 
	*/

    /**
     * 微信接受消息验证
     *
     * @param token
     * @param signature
     * @param timestamp
     * @param nonce
     * @return
     */
    public boolean checkSignature(String token, String signature, String timestamp, String nonce) {
        logger.info(Constants.LOGPRIFIX + "token=" + token + ",signature=" + signature + ",timestamp=" + timestamp + ",nonce=" + nonce);
        if (token == null || signature == null || timestamp == null || nonce == null) {
            return false;
        }
        try {
            String array[] = new String[]{token, timestamp, nonce};
            StringBuffer sb = new StringBuffer();
            //字符排序
            Arrays.sort(array);
            for (int i = 0; i < 3; i++) {
                sb.append(array[i]);
            }
            String str = sb.toString();
            MessageDigest md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.getBytes());
            String outerStr = byteToString(digest);
            logger.info(Constants.LOGPRIFIX + "signature=" + signature + ",outerStr=" + outerStr);
            if (signature.equals(outerStr)) {
                return true;
            }
        } catch (NoSuchAlgorithmException e) {
            logger.warn(JDKStackTrace.getJDKStrack(e));
        } catch (Exception e) {
            logger.warn(JDKStackTrace.getJDKStrack(e));
        }
        return false;
    }

    /**
     * byte[] 转 String
     *
     * @param digest
     * @return
     */
    private String byteToString(byte[] digest) {
        StringBuffer hexstr = new StringBuffer();
        String shaHex = "";
        for (int i = 0; i < digest.length; i++) {
            shaHex = Integer.toHexString(digest[i] & 0xFF);
            if (shaHex.length() < 2) {
                hexstr.append(0);
            }
            hexstr.append(shaHex);
        }
        return hexstr.toString();
    }
}
